// User class

/* Constructs a new User data structure with data from Storage */
function User(fromStorage) {
	/* search history: A list of strings */
	var searches = fromStorage ? fromStorage.searches : [];
	
	/* rental history: A list of rentals. Current rental on top */
	var rentals = fromStorage ? fromStorage.rentals : [];
	
	/* interests: A map of movies user is interested in */
	var interests = fromStorage ? fromStorage.interests : {};
	
	/* getters */
	
	this.__defineGetter__("searches", function() {
		return searches;
	});
	
	this.__defineGetter__("rentals", function() {
		return rentals;
	});
	
	this.__defineGetter__("interests", function() {
		return interests;
	});
}

/* Adds a new search to a user's search history */
User.prototype.addSearch = function(newSearch) {
	var index = this.searches.indexOf(newSearch);
	
	/* push newSearch to the top of the list */
	if(index != -1) {
		this.searches.splice(index, 1); // remove old
	}
	
	this.searches.push(newSearch); // place to top
}

/* Adds a new rental to user's rental history */
User.prototype.addRental = function(movieId) {
	var index = this.rentals.indexOf(movieId);
	
	/* push movieId to top of the list */
	if(index != -1) {
		this.rentals.splice(index, 1); // remove old
	}
	
	this.rentals.push(movieId); // place on top
}

/* Show interest in a film. 1.0 means user likes the film */
User.prototype.rateMovie = function(movieId, rating) {
	// key must be string, value must be a float
	this.interests[movieId.toString()] = rating;
}

/* Show interest in a film. 1.0 means user likes the film */
User.prototype.incMovie = function(movieId, factor) {
	// key must be string, value must be a float
	if( movieId.toString() in this.interests)
		this.interests[movieId.toString()] =
			1 - (1 - this.interests[movieId.toString()]) / Math.pow(2, 1.0 / factor);
	else
		this.interests[movieId.toString()] = 1 - Math.pow(2, -1.0 / factor);
}

User.prototype.recommendations = function() {
	TmdbConnection.getRecommendations(this);
}

/* Static method to read user from localStorage */
User.read = function() {
	var userJson = localStorage.getItem("user");
	
	return new User(JSON.parse(userJson));
}

/* Static method to write user to localStorage */
User.write = function(user) {
	var userJson = JSON.stringify(new User(user));
	
	localStorage.setItem("user", userJson);
}